package org.softmed.ATComm.swingClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.restlet.Client;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.data.Response;
import org.restlet.resource.StringRepresentation;

public class DefaultRESTletClient implements RESTClient {

	Client client = new Client(Protocol.HTTP);

	String serialPortListURL = "/serialports";
	String serialPortURL = "/serialport";
	String smsURL = "/sms";

	String baseAddress;

	@Override
	public String getURL() {
		return baseAddress;
	}

	@Override
	public void setURL(String url) {
		baseAddress = url;
	}

	@Override
	public List<String> getSerialPorts() throws Throwable {
		Response response = client.get(baseAddress + serialPortListURL);
		String text = response.getEntity().getText();

		if (text.contains("ERROR") || text.contains("<html>"))
			throw new RuntimeException("Couldn't get the serial port list");

		List<String> ports = new ArrayList<String>();

		StringTokenizer st = new StringTokenizer(text);
		while (st.hasMoreTokens()) {
			ports.add(st.nextToken());
		}

		return ports;
	}

	@Override
	public String getSerialPortName() throws Throwable {
		Response response = client.get(baseAddress + serialPortURL);

		String text = response.getEntity().getText();
		if (text.contains("ERROR"))
			throw new RuntimeException("Coudln't get the serial port");
		return text;
	}

	@Override
	public void setSerialPortName(String port) throws Throwable {
		Response response = client.put(baseAddress + serialPortURL,
				new StringRepresentation(port, MediaType.TEXT_PLAIN));

		String text = response.getEntity().getText();
		if (text.contains("ERROR"))
			throw new RuntimeException("Coudln't get the serial port");
	}

	@Override
	public void sendSMS(String number, String message) throws Throwable {
		Response response = client.put(baseAddress + smsURL,
				new StringRepresentation(number + '\n' + message,
						MediaType.TEXT_PLAIN));

		String text = response.getEntity().getText();
		if (text.contains("ERROR"))
			throw new RuntimeException(text);

	}

}
